<template>
  <div class="root">
    <div class="top">
      <a-icon-font
        class="icon"
        :type="cell.type === 1 ? 'iconsuanfa1' : 'iconmoxing'"
      ></a-icon-font>
      <span class="model-name">{{ cell.name }}</span>

      <div class="right-items">
        <a-button @click.stop="statistics">统计</a-button>
        <!-- <a-button v-else disabled @click.stop="viewCode">查看源码</a-button> -->
        <a-button
          type="primary"
          style="margin-left: 16px;"
          :disabled="cell.install"
          :loading="instalLoading"
          @click.stop="install"
          >{{ cell.install ? '已安装' : '安装' }}</a-button
        >
      </div>
    </div>
    <div class="content">
      <!-- <a-icon-font class="left-block" :type="cell.icon"></a-icon-font> -->
      <img class="left-block" :src="cell.cover ? cell.cover : defaulCover" />
      <div class="right-block">
        <div style="display: flex;">
          <!-- <span class="font-title" style="min-width: 56px;">介绍：</span> -->
          <div class="description">{{ cell.summary }}</div>
        </div>
        <a-row>
          <a-col :span="12">
            <span class="font-title"
              >最新发布时间：<span class="font-content">{{
                cell.publicTime ? cell.publicTime : '-'
              }}</span></span
            >
          </a-col>
          <a-col :span="12">
            <span class="font-title"
              >版本号：<span class="font-content">{{
                cell.version
              }}</span></span
            >
          </a-col>
        </a-row>
        <a-row type="flex" class="bottom-content">
          <a-col flex="auto" class="key-words">
            <span class="font-title">关键词：</span>
            <a
              v-for="keyword in cell.keyword.split(',')"
              :key="keyword"
              class="key"
              @click.stop="searchKey(keyword)"
              >{{ keyword }}</a
            >
          </a-col>
          <a-col type="auto" class="owner" align="right">
            <a-avatar
              class="avtar"
              :src="cell.profile ? cell.profile : defaultAvatar"
            />
            <span class="font-content">{{ cell.owner }}</span>
          </a-col>
        </a-row>
      </div>
    </div>

    <a-modal
      :visible="modalVisible"
      :keyboard="true"
      :cancel-text="'取消'"
      :ok-text="'确认'"
      :centered="true"
      :destroy-on-close="true"
      @ok="closeModal"
      @cancel="closeModal"
    >
      <div class="modal-content">
        <div class="modal-title">
          <a-icon-font class="modal-icon" type="iconweiwanpeizhi"></a-icon-font
          ><strong style="width: 100%;">版本冲突！</strong>
        </div>
        <div class="modal-body">
          <p>
            您已安装【{{ cell.name }}】{{
              cell.version
            }}版本，本次安装的版本号为：{{
              cell.version
            }}，请选择您要安装的方式：
          </p>
          <a-radio-group v-model="radioValue">
            <a-radio :value="'add'" style="margin-bottom: 4px;">
              新增，保留旧版本内容
            </a-radio>
            <br />
            <a-radio :value="'cover'">
              覆盖，删除旧版本内容
            </a-radio>
          </a-radio-group>
        </div>
      </div>
    </a-modal>

    <!-- 统计 -->
    <a-modal
      :visible="stasVisible"
      :keyboard="true"
      :centered="true"
      :destroy-on-close="true"
      :title="`统计-${cell.name}`"
      width="655px"
      @cancel="closeModal"
    >
      <div class="statistics">
        <a-radio-group v-model="range" class="tabs" button-style="solid">
          <a-radio-button value="week">近一周</a-radio-button>
          <a-radio-button value="month">近一月</a-radio-button>
          <a-radio-button value="year">近一年</a-radio-button>
        </a-radio-group>
        <div class="divider" />
        <span class="normal">自定义：</span>
        <a-range-picker
          v-model="dateRange"
          :placeholder="['开始日期', '结束日期']"
          value-format="YYYY-MM-DD 00:00:00"
        />
      </div>
      <a-spin :spinning="loading">
        <div v-if="chartData.length < 1" class="empty" align="center">
          <img alt="" height="154px" src="@/assets/view/empty2.png" />
        </div>
        <div v-else class="chart">
          <Chart :chart-type="'lineChart'" :config="commonConfig" />
        </div>
      </a-spin>
      <template slot="footer">
        <a-button type="primary" @click="closeModal">关闭</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import { statisticsModel, installModel } from '@/api/plugin'
import Chart from '@/components/chart/chart.vue'

export default {
  name: 'ModelCell',
  components: { Chart },
  props: {
    cell: Object,
  },
  data() {
    return {
      isCollect: false,
      modalVisible: false,
      radioValue: 'add',
      stasVisible: false,
      dateRange: [],
      range: 'month',
      precision: 'day',
      loading: false,
      chartData: [],
      defaulCover: require('@/assets/default.png'),
      defaultAvatar: require('@/assets/user/avatar0.png'),
      instalLoading: false,
    }
  },
  computed: {
    commonConfig() {
      return {
        value: this.chartData,
        labelKey: 'x',
        valueKey: '浏览量',
        xAxisAttribute: 'x',
        yAxisAttribute: ['浏览量', '下载量', '收藏量'],
        xAxisFontSize: 12,
        xAxisTitleIsShow: false,
        yAxisTitleIsShow: false,
        xAxisTitle: '时间',
        yAxisTitle: '数量',
        legendPosition: 'top',
        labelIsShow: false,
      }
    },
  },
  watch: {
    dateRange() {
      if (this.dateRange.length > 0) {
        this.queryStatistics()
      }
    },
    range() {
      this.selectRange(this.range)
    },
  },
  mounted() {},
  created() {},
  methods: {
    callback() {},
    onSearch() {},
    download() {},
    collect() {
      this.isCollect = !this.isCollect
    },
    searchKey(value) {
      this.$emit('search-keyword', value)
    },
    async install() {
      // this.modalVisible = true
      this.instalLoading = true
      try {
        const response = await installModel({ data: { id: this.cell.id } })
        this.instalLoading = false
        if (response.data.code === 100) {
          this.$message.success('安装成功！请到【我的-社区-本地已安装】查看')
          this.$emit('update-list')
        } else {
          this.$message.error(response.data.message)
        }
      } catch {
        this.instalLoading = false
      }
    },
    selectRange(value) {
      switch (value) {
        case 'week':
          {
            const end = new Date()
            end.setHours(23)
            end.setMinutes(59)
            end.setSeconds(59)
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 6)
            start.setHours(0)
            start.setMinutes(0)
            start.setSeconds(0)
            this.dateRange = [
              `${start.toLocaleDateString().replace(/\//g, '-')} 00:00:00`,
              `${end.toLocaleDateString().replace(/\//g, '-')} 00:00:00`,
            ]
          }
          break
        case 'month':
          {
            const end = new Date()
            end.setHours(23)
            end.setMinutes(59)
            end.setSeconds(59)
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 29)
            start.setHours(0)
            start.setMinutes(0)
            start.setSeconds(0)
            this.dateRange = [
              `${start.toLocaleDateString().replace(/\//g, '-')} 00:00:00`,
              `${end.toLocaleDateString().replace(/\//g, '-')} 00:00:00`,
            ]
          }
          break
        case 'year':
          {
            const end = new Date()
            end.setHours(23)
            end.setMinutes(59)
            end.setSeconds(59)
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 365)
            start.setHours(0)
            start.setMinutes(0)
            start.setSeconds(0)
            this.dateRange = [
              `${start.toLocaleDateString().replace(/\//g, '-')} 00:00:00`,
              `${end.toLocaleDateString().replace(/\//g, '-')} 00:00:00`,
            ]
          }
          break
        default:
          break
      }
    },
    statistics() {
      this.stasVisible = true
      this.selectRange('month')
    },
    viewCode() {},
    closeModal() {
      this.modalVisible = false
      this.radioValue = 'add'
      this.range = 'month'

      this.stasVisible = false
    },
    async queryStatistics() {
      this.loading = true
      const dayCount =
        (new Date(this.dateRange[1]) - new Date(this.dateRange[0])) /
          3600000 /
          24 +
        1
      if (dayCount <= 30) {
        this.precision = 'day'
      } else if (dayCount > 30 && dayCount <= 180) {
        this.precision = 'week'
      } else {
        this.precision = 'month'
      }

      const response = await statisticsModel({
        data: {
          id: this.cell.id,
          start: this.dateRange[0],
          end: this.dateRange[1],
          precision: this.precision,
        },
      })
      this.loading = false
      if (response.data.code === 100) {
        this.chartData = []
        const { result } = response.data
        result[Object.keys(result)[0]].forEach((element, index) => {
          const item = {
            下载量: result.download[index],
            收藏量: result.favor[index],
            浏览量: result.watch[index],
            x: result.x[index],
          }
          this.chartData.push(item)
        })
      }
    },
  },
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
/deep/.ant-modal-footer {
  border-top: 0;
}

/deep/ .ant-btn {
  border-radius: 4px;
}

/deep/.ant-modal-footer {
  border-top: 1px solid #e8e8e8 !important;
}

.ant-radio-group-solid
  .ant-radio-button-wrapper-checked:not(.ant-radio-button-wrapper-disabled) {
  background: #6973ff;
  background: #6973ff;
  border-color: #6973ff;
  color: #fff;
}

.ant-radio-button-wrapper:hover {
  background-color: #f0f1ff;
  color: #6973ff;
  position: relative;
}

.root {
  border-bottom: 1px solid #e8e8e8;
  // font-family: PingFangSC-Regular, PingFang SC;
  min-height: 156px;
  min-width: 690px;
  width: 100%;

  .font-title {
    color: #5d637e;
  }

  .font-content {
    color: #373b52;
  }

  .font-primary {
    color: #6973ff;
  }

  .top {
    align-items: center;
    display: flex;
    margin-bottom: 12px;
    position: relative;

    .icon {
      font-size: 18px;
      margin-right: 8px;
    }

    .model-name {
      // font-family: PingFangSC-Medium, PingFang SC;
      font-size: 16px;
    }

    .buttons {
      position: absolute;
      right: 0;
    }

    .right-items {
      align-items: center;
      display: flex;
      // font-family: PingFangSC-Light, PingFang SC;
      position: absolute;
      right: 0;
      top: 0;

      .avadar {
        font-size: 18px;
      }

      .name {
        margin-left: 4px;
        margin-right: 32px;
      }
    }
  }

  .content {
    position: relative;

    .left-block {
      height: 96px;
      // font-size: 96px;
      left: 0;
      position: absolute;
      width: 96px;
    }

    .right-block {
      height: 96px;
      left: 128px;
      position: absolute;
      width: calc(100% - 128px);
      /* stylelint-disable  */
      .description {
        // 只显示3行文字
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 3;
        line-clamp: 3;
        overflow: hidden;
        text-align: left;
        text-overflow: -o-ellipsis-lastline;
        // height: 60px;
        width: 100%;
      }
      /* stylelint-enable  */

      .bottom-content {
        bottom: 0;
        position: absolute;
        width: 100%;

        .key-words {
          display: flex;
          text-align: left;

          .key {
            color: #6973ff;
            margin-right: 16px;
          }
        }

        .owner {
          align-items: center;
          display: flex;

          .avtar {
            height: 18px;
            margin-right: 8px;
            width: 18px;
          }
        }
      }
    }
  }
}

.modal-content {
  padding: 32px 32px 0;
  width: 100%;

  .modal-title {
    align-items: center;
    display: flex;
    font-size: 16px;
    margin-bottom: 20px;
    width: 100%;

    .modal-icon {
      font-size: 24px;
      margin-right: 14px;
    }
  }

  .modal-body {
    margin-left: 40px;
  }

  p {
    color: #5d637e;
  }
}

.statistics {
  align-items: center;
  display: flex;
  white-space: nowrap;

  .divider {
    background: #e9e9e9;
    height: 18px;
    margin: 0 16px;
    width: 1px;
  }

  .tabs {
    border-radius: 4px;
  }

  .noarmal {
    color: #5d637e;
  }

  .primary {
    color: #6973ff;
    cursor: pointer;
    margin-left: 16px;
  }
}

.options {
  align-items: center;
  display: flex;
  margin: 24px 0;
  white-space: nowrap;
}

.chart {
  height: 400px;
  margin-left: -24px;
  margin-top: 24px;
  width: 655px;
}
</style>
